package com.taoshen.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.taoshen.entity.User;
import com.taoshen.util.JWTUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author Zhang Litao
 * @Date 2021/11/18 11:20
 */
@RestController
@RequestMapping("jwt")
public class JWTController {
    AtomicInteger count = new AtomicInteger();

    /**
     * 登录接口 生成token返回给前端
     */
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody User user) {
        try {
            Map<String, Object> resultMap = MapUtil.newHashMap();

            Dict payload = new Dict()
                    .set("username", user.getUsername())
                    .set("role", user.getRole());

            String token = JWTUtils.getToken(payload);

            resultMap.put("code", 200);
            resultMap.put("msg", "登录成功");
            resultMap.put("token", token);
            return resultMap;
        } finally {
            StaticLog.info("当前已经访问量 => {}", count.incrementAndGet());
        }
    }


    @GetMapping("test")
    public Map<String, Object> test(HttpServletRequest request) {
        Map<String, Object> resultMap = MapUtil.newHashMap();

        Map<String, Object> token = JWTUtils.getPayload(request.getHeader("token"));
        token.forEach((k, v) -> System.out.println(k + " : " + v));

        System.out.println("加油");
        System.out.println("加油");
        System.out.println("加油");
        System.out.println("加油");
        System.out.println("加油");

        resultMap.put("msg", "响应成功");
        resultMap.put("code", 200);
        return resultMap;
    }
}
